﻿using UnityEngine;
using System.Collections;

namespace UnityEngine.UI
{
    public class EmptyRaycast : MaskableGraphic
    {
        public Mask m_Mask;    // 缓存mask组件，如果后面有动态添加，记得set一下
        protected override void Awake()
        {
            base.Awake();

            //m_Mask = GetComponent<Mask>();
            var cr = canvasRenderer;
        }

        protected EmptyRaycast()
        {
            useLegacyMeshGeneration = false;
        }

        public Mask CachedMask
        {
            get
            {
                return m_Mask;
            }
            set
            {
                m_Mask = value;
            }
        }

        protected override void OnPopulateMesh(VertexHelper toFill)
        {
            toFill.Clear();
        }

        /// <summary>
        /// 重写这个MaskableGraphic的虚函数，默认实现的getcomponent很耗
        /// </summary>
        /// <param name="baseMaterial"></param>
        /// <returns></returns>
        public override Material GetModifiedMaterial(Material baseMaterial)
        {
            var toUse = baseMaterial;

            if (m_ShouldRecalculateStencil)
            {
                var rootCanvas = MaskUtilities.FindRootSortOverrideCanvas(transform);
                m_StencilValue = maskable ? MaskUtilities.GetStencilDepth(transform, rootCanvas) : 0;
                m_ShouldRecalculateStencil = false;
            }

            // if we have a Mask component then it will
            // generate the mask material. This is an optimisation
            // it adds some coupling between components though :(
            if (m_StencilValue > 0 && CachedMask == null)
            {
                var maskMat = StencilMaterial.Add(toUse, (1 << m_StencilValue) - 1, UnityEngine.Rendering.StencilOp.Keep, UnityEngine.Rendering.CompareFunction.Equal, UnityEngine.Rendering.ColorWriteMask.All, (1 << m_StencilValue) - 1, 0);
                StencilMaterial.Remove(m_MaskMaterial);
                m_MaskMaterial = maskMat;
                toUse = m_MaskMaterial;
            }
            return toUse;
        }
    }
}